//
//  CZ NetworkTool.swift
//  Weibo
//
//  Created by 铭铭 on 15/11/26.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

import AFNetworking

//网络单例
class CZNetworkTool: AFHTTPSessionManager {
    
    // 单例
    static let sharedInsatance: CZNetworkTool = {
        
         let baseURL = NSURL(string: "https://api.weibo.com/")
        
         let tool = CZNetworkTool(baseURL: baseURL)
     
        // 添加响应的序列化器
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")

        return tool
   }()
//MARK:- Oauth授权
    /// 申请应用时分配的AppKey
   private let client_id = "2119629487"
    
    /// 申请应用时分配的AppSecret
   private let client_secret = "1b9cd93ce78a870c8818e9f23798aeea"
    
    /// 授权回调地址, 一定要一模一样
    let redirect_uri = "http://www.baidu.com/"
    
    //授权界面的URL地址
    func oauthURL() -> NSURL{
    // GET方式拼接登录界面请求地址
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        return NSURL(string: urlString)!
    }
    
//MARK: 加载Access Token
    func loadAccessToken(code:String, finished: (result:[String: AnyObject]?, error:NSError?)->()){
        // api地址
        let urlString = "https://api.weibo.com/oauth2/access_token"
    
        //post参数
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]

        // 发送POST请求
       POST(urlString, parameters: parameters, success: { (_, result) -> Void in
        
        // as! 强制转换,f 有风险,如果转换不了,直接崩溃
        // as? 如果能转成功就转换,如果不能转换就返回nil
        
        finished(result: result as? [String : AnyObject], error: nil)
        
      
        }) { (_, error) -> Void in
            
        finished(result: nil, error:error)
            
        }
        
    
    }
    
    
}
